/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.reagentclass.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsMapper;
import vip.xiaonuo.biz.modular.reagentclass.entity.BizReagentClass;
import vip.xiaonuo.biz.modular.reagentclass.mapper.BizReagentClassMapper;
import vip.xiaonuo.biz.modular.reagentclass.param.ReagentClassQryDto;
import vip.xiaonuo.biz.modular.reagentclass.result.ReagentClassPageResult;
import vip.xiaonuo.biz.modular.reagentclass.service.BizReagentClassService;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 试剂品类表Service接口实现类
 *
 * @author levin
 * @date 2023/04/13 10:40
 **/
@Service
@Transactional
public class BizReagentClassServiceImpl extends ServiceImpl<BizReagentClassMapper, BizReagentClass> implements BizReagentClassService {

    @Resource
    private BizGoodsMapper bizGoodsMapper;

    @Override
    public Page<ReagentClassPageResult> page(ReagentClassQryDto dto) {
        return this.baseMapper.getPageList(CommonPageRequest.defaultPageForDto(dto), dto);
    }

    @Override
    public void add(BizReagentClass entity) {
        //校验重复编号
        List<BizReagentClass> list = this.getByName(entity.getCasNo(), null);
        if (!CollectionUtils.isEmpty(list)) {
            throw new CommonException("试剂名称已存在，请重新输入！");
        }
        this.save(entity);
    }

    @Override
    public void edit(BizReagentClass entity) {
        //校验重复编号
        List<BizReagentClass> list = this.getByName(entity.getCasNo(), entity.getId());
        if (!CollectionUtils.isEmpty(list)) {
            throw new CommonException("试剂名称已存在，请重新输入！");
        }
        this.updateById(entity);
        //更新对应的试剂名称
        bizGoodsMapper.updateNameByReagentClassId(entity.getReagentName(),entity.getId());
    }

    @Override
    public void delete(BizReagentClass entity) {
        this.removeById(entity.getId());
    }

    @Override
    public BizReagentClass detail(ReagentClassQryDto dto) {
        return this.getById(dto.getId());
    }

    @Override
    public List<ReagentClassPageResult> list(ReagentClassQryDto dto) {
        return this.baseMapper.getList(dto);
    }

    @Override
    public int upload(MultipartFile file) {
        int result = 0;
        try {
            ExcelReader reader = reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> dataList = reader.read();
            int index = 1;
            if (dataList.size() < 3) {
                throw new CommonException("导入文件无数据，请添加数据");
            }
            List<BizReagentClass> reagentClassList = new ArrayList<>();
            for (int i = 2; i < dataList.size(); i++) {
                List<Object> item = dataList.get(i);
                int rowNum = i + 1;
                BizReagentClass reagentClass = new BizReagentClass();

                String reagentName = null;
                if (null == item.get(1)) {
                    throw new CommonException("第" + rowNum + "行数据，名称为空，请核对数据");
                } else {
                    reagentName = item.get(1).toString();
                    List<BizReagentClass> list = this.getByName(reagentName, null);
                    if (!CollectionUtils.isEmpty(list)) {
                        throw new CommonException("第" + rowNum + "行数据，名称：" + reagentName + " 已存在，请核对数据");
                    }
                }

                String casNo = null;
                if (null == item.get(2)) {
                    throw new CommonException("第" + rowNum + "行数据，CAS号为空，请核对数据");
                } else {
                    casNo = item.get(2).toString();
                }

                String classId = null;
                if (null == item.get(3)) {
                    throw new CommonException("第" + rowNum + "行数据，类型为空，请核对数据");
                } else {
                    classId = this.baseMapper.getDictValueByLabel(item.get(3).toString(), "1642353896092790785");
                    if (StringUtils.isBlank(classId)) {
                        throw new CommonException("第" + rowNum + "行数据，类型：" + item.get(3).toString() + " 未在字典中维护，请维护字典数据");
                    }
                }

                String density = null;
                if (null == item.get(4)) {
                    throw new CommonException("第" + rowNum + "行数据，密度为空，请核对数据");
                } else {
                    if (!NumberUtil.isNumber(item.get(4).toString())) {
                        throw new CommonException("第" + rowNum + "行数据，密度：" + item.get(4).toString() + " 非数字类型，请核对数据");
                    } else {
                        density = item.get(4).toString();
                    }
                }

                String formId = null;
                if (null == item.get(5)) {
                    throw new CommonException("第" + rowNum + "行数据，形态为空，请核对数据");
                } else {
                    formId = this.baseMapper.getDictValueByLabel(item.get(5).toString(), "1646346559636250626");
                    if (StringUtils.isBlank(classId)) {
                        throw new CommonException("第" + rowNum + "行数据，形态：" + item.get(5).toString() + " 未在字典中维护，请维护字典数据");
                    }
                }

                String bottleType = null;
                if (null == item.get(6)) {
                    throw new CommonException("第" + rowNum + "行数据，试剂瓶类型为空，请核对数据");
                } else {
                    bottleType = this.baseMapper.getDictValueByLabel(item.get(6).toString(), "1646347515807539201");
                    if (StringUtils.isBlank(classId)) {
                        throw new CommonException("第" + rowNum + "行数据，试剂瓶类型：" + item.get(6).toString() + " 未在字典中维护，请维护字典数据");
                    }
                }

                String redoxClassId = null;
                if (null == item.get(7)) {
                    throw new CommonException("第" + rowNum + "行数据，氧化还原类型为空，请核对数据");
                } else {
                    redoxClassId = this.baseMapper.getDictValueByLabel(item.get(7).toString(), "1646347109555642369");
                    if (StringUtils.isBlank(classId)) {
                        throw new CommonException("第" + rowNum + "行数据，氧化还原类型：" + item.get(7).toString() + " 未在字典中维护，请维护字典数据");
                    }
                }

                String unit = null;
                if (null == item.get(8)) {
                    throw new CommonException("第" + rowNum + "行数据，试剂单位为空，请核对数据");
                } else {
                    if (item.get(8).toString().equals("毫升")) {
                        unit = "0";
                    } else if (item.get(8).toString().equals("克")) {
                        unit = "1";
                    } else {
                        throw new CommonException("第" + rowNum + "行数据，试剂单位：" + item.get(8).toString() + " 无法识别，请核对数据");
                    }
                }

                String maxErrorValue = null;
                if (null == item.get(9)) {
                    throw new CommonException("第" + rowNum + "行数据，误差最大值为空，请核对数据");
                } else {
                    if (!NumberUtil.isNumber(item.get(9).toString())) {
                        throw new CommonException("第" + rowNum + "行数据，误差最大值：" + item.get(9).toString() + " 非数字类型，请核对数据");
                    } else {
                        maxErrorValue = item.get(9).toString();
                    }
                }

                String maxLimitLeave = null;
                if (null != item.get(10)) {
                    if (!NumberUtil.isNumber(item.get(10).toString())) {
                        throw new CommonException("第" + rowNum + "行数据，最大离柜时限：" + item.get(10).toString() + " 非数字类型，请核对数据");
                    } else {
                        maxLimitLeave = item.get(10).toString();
                    }
                }

                String weighNeedFlag = null;
                if (null == item.get(11)) {
                    throw new CommonException("第" + rowNum + "行数据，是否称重为空，请核对数据");
                } else {
                    if (item.get(11).toString().equals("否")) {
                        weighNeedFlag = "0";
                    } else if (item.get(11).toString().equals("是")) {
                        weighNeedFlag = "1";
                    } else {
                        throw new CommonException("第" + rowNum + "行数据，是否称重：" + item.get(8).toString() + " 无法识别，请核对数据");
                    }
                }

                String remarks = null;
                if (null != item.get(12)) {
                    remarks = item.get(12).toString();
                }

                String msdsDesc = null;
                if (null != item.get(13)) {
                    msdsDesc = item.get(13).toString();
                }

                reagentClass.setCasNo(casNo);
                reagentClass.setReagentName(reagentName);
                reagentClass.setClassId(classId);
                reagentClass.setFormId(formId);
                reagentClass.setUnit(unit);
                reagentClass.setDensity(new BigDecimal(density));
                reagentClass.setRedoxClassId(redoxClassId);
                reagentClass.setMaxLimitLeave(maxLimitLeave);
                reagentClass.setWeighNeedFlag(weighNeedFlag);
                reagentClass.setMaxErrorValue(new BigDecimal(maxErrorValue));
                reagentClass.setBottleType(bottleType);
                reagentClass.setRemarks(remarks);
                reagentClass.setMsdsDesc(msdsDesc);
                reagentClassList.add(reagentClass);
            }
            if (!CollectionUtils.isEmpty(reagentClassList)) {
                result = reagentClassList.size();
                this.saveBatch(reagentClassList);
            }
        } catch (IOException e) {
            throw new CommonException("导入文件解析失败");
        }
        return result;
    }

    /**
     * 根据编号获取lsit 校验用
     *
     * @param code
     * @param id
     * @return
     */
    private List<BizReagentClass> getByCasNo(String casNo, String id) {
        QueryWrapper<BizReagentClass> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(id)) {
            queryWrapper.lambda().ne(BizReagentClass::getId, id);
        }
        queryWrapper.lambda().eq(BizReagentClass::getCasNo, casNo);
        queryWrapper.lambda().eq(BizReagentClass::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        return this.list(queryWrapper);
    }

    /**
     * 根据编号获取lsit 校验用
     *
     * @param code
     * @param id
     * @return
     */
    private List<BizReagentClass> getByName(String name, String id) {
        QueryWrapper<BizReagentClass> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(id)) {
            queryWrapper.lambda().ne(BizReagentClass::getId, id);
        }
        queryWrapper.lambda().eq(BizReagentClass::getReagentName, name.trim());
        queryWrapper.lambda().eq(BizReagentClass::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        return this.list(queryWrapper);
    }
}
